package com.polaris.live.widget

import android.R
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.core.PositionPopupView
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.databinding.PopupPushNoticeBinding
import com.polaris.live.im.utils.SessionUtils
import com.polaris.live.resp.bean.PromptNoticeBean
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.utils.image.loadImage
import com.polaris.live.utils.image.transformRounded
import com.polaris.live.utils.route.RouterUtils
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.abs

/**
 * PushNoticeView
 *
 * @author Created by 天晴 on 2024/8/16 10:07
 * @since 1.0.0
 **/
class PushNoticeView(val context: Context, val message: PromptNoticeBean, val dismissBlock: () -> Unit) :
    DefaultLifecycleObserver {

    private var dismissJob: Job? = null

    private var ty: Float = 0f
    private var ty2: Float = 0f
    private var isCancel = false
    private var isAmin = false

    private var mInAnim: ObjectAnimator? = null
    private var mOutAnim: ObjectAnimator? = null
    fun show() {
        initView()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        if (context is AppCompatActivity && !context.isFinishing && !context.isDestroyed) { //是activity 且沒有關閉
            val cv: View = context.window.decorView.findViewById(R.id.content)
            cv.post {
                //view实现
                val decorView = context.window.decorView as ViewGroup
                val mBinding = PopupPushNoticeBinding.inflate(LayoutInflater.from(context), null, false)
                val lp =
                    ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                val lp2 = mBinding.cvBg.layoutParams as FrameLayout.LayoutParams
                lp2.topMargin = BarUtils.getStatusBarHeight()
                mBinding.cvBg.layoutParams = lp2
                decorView.addView(mBinding.root, lp)
                setDataView(mBinding)

                inAnim(mBinding.root)

                mBinding.cvBg.setOnTouchListener { _, event ->
                    if (isAmin) {
                        return@setOnTouchListener false
                    }
                    when (event.action) {
                        MotionEvent.ACTION_DOWN -> {
                            ty = event.rawY
                            ty2 = event.rawY
                        }

                        MotionEvent.ACTION_MOVE -> {
                            val y = event.rawY
                            val indexc = y - ty
                            if (indexc < 0) {
                                if (abs(indexc) > 50) {
                                    isCancel = true
                                    outAnim(mBinding.root)
                                    return@setOnTouchListener true
                                }
                                mBinding.root.scrollBy(0, (ty2 - y).toInt())
                                ty2 = y
                            }
                        }

                        MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                            if (isCancel) {
                                return@setOnTouchListener true
                            }
                        }
                    }
                    false
                }


                dismissJob = CoroutineScopeManager.mainScope.launch {
                    try {
                        delay(3000)
                        outAnim(mBinding.root)
                    } finally {
                        if (dismissJob == coroutineContext[Job]) {
                            dismissJob = null
                        }
                    }
                }
            }
            context.lifecycle.addObserver(this)

        }
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        dismissBlock.invoke()
        release()

    }

    private fun release() {
        mOutAnim?.cancel()
        mInAnim?.cancel()
        mInAnim = null
        mOutAnim = null
        dismissJob?.cancel()
        dismissJob = null
        if (context is AppCompatActivity) {
            context.lifecycle.removeObserver(this)
        }
    }

    /**
     * 进入动画
     */
    private fun inAnim(view: View) {
        isAmin = true
        mInAnim = ObjectAnimator.ofFloat(view, "translationY", (-120).autoDp.toFloat(), 0f)
        mInAnim?.duration = 200
        mInAnim?.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                isAmin = false
            }
        })
        mInAnim?.start()
    }

    /**
     * 退出动画
     */
    private fun outAnim(view: View) {
        isAmin = true
        mOutAnim = ObjectAnimator.ofFloat(view, "translationY", 0f, (-120).autoDp.toFloat())
        mOutAnim?.duration = 200
        mOutAnim?.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                isAmin = false
                dismissBlock.invoke()
                release()
                if (context is AppCompatActivity && !context.isFinishing && !context.isDestroyed)
                    (context.window.decorView as ViewGroup).apply {
                        post {
                            removeView(view)
                        }
                    }
            }
        })
        mOutAnim?.start()
    }

    private fun setDataView(mBinding: PopupPushNoticeBinding) {
        mBinding.tvTime.text =
            StringUtils.getString(com.polaris.live.translation.R.string.app_name) + " " + SessionUtils.formatSessionTime(
                message.timestamp
            )

        if (message.title.isNullOrEmpty()) {
            mBinding.tvTitle.visibility = PositionPopupView.GONE
        } else {
            mBinding.tvTitle.text = message.title
        }

        mBinding.tvContent.text = message.content

        if (message.image.isNullOrEmpty()) {
            mBinding.ivImage.visibility = PositionPopupView.GONE
        } else {
            Glide.with(context)
                .loadImage(message.image)
                .transformRounded(4.dp)
                .into(mBinding.ivImage)
        }

        mBinding.cvBg.setOnSingleClickListener {
            if (isAmin) {
                return@setOnSingleClickListener
            }
            SnackbarUtils.dismiss()
            if (!PartyUserStateUtil.clickUser()) {
                return@setOnSingleClickListener
            }
            if (message.router != null) {
                RouterUtils.routerGoto(message.router)
            }
            if (message.router2 != null) {
                RouterUtils.routerGoto(message.router2)
            }
        }

    }
}